package com.hefan.api.controller.H5;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.google.common.collect.Maps;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.service.oms.RechargeLocalService;
import com.hefan.oms.itf.PlatformRechargeService;
import com.hefan.user.bean.WebUser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangchao
 * @create 2017/2/8 15:33
 */
@Controller
@RequestMapping("/v1/h5")
public class H5RechargeCodeController {
  @Resource
  private RechargeLocalService rechargeLocalService;
  @Resource
  private UserLocalService userService;
  @Reference
  PlatformRechargeService platformRechargeService;

  public Logger logger = LoggerFactory.getLogger(H5RechargeCodeController.class);

  /**
   * h5兑换码充值查询充值码
   *
   * @param request
   * @return
   * @throws
   * @description （用一句话描述该方法的适用条件、执行流程、适用方法、注意事项 - 可选）
   * @author wangchao
   * @create 2017/2/8 15:33
   */
  @RequestMapping(value = "validate", method = RequestMethod.GET)
  @ResponseBody
  public ResultBean validate(HttpServletRequest request) {
    Map<String, Object> map = Maps.newHashMap();
    try {
      //1.充值码
      String rechargeCode = request.getParameter("code");
      String userId = request.getParameter("userId");
      logger.info("PC查询充值码{}", rechargeCode);
      //2.校验参数是否为空
      if (StringUtils.isBlank(rechargeCode) || StringUtils.isBlank(userId) ) {
        logger.error("PC充值码充值参数为空");
        return new ResultBean(ResultCode.ParamException);
      }
      //3.验证充值码是否可用

      ResultBean checkResult = rechargeLocalService.findValidRechargeInfoByCode(rechargeCode,userId);
      if (checkResult.getCode() != ResultCode.SUCCESS.get_code()) {
        logger.error("PC充值码充值,充值码{}不可用", rechargeCode);
        return checkResult;
      }
      Map rechargeMap = (Map)checkResult.getData();
      //4.获取充值码对应的充值金额
      Integer kindNameIn = Integer.valueOf(String.valueOf(rechargeMap.get("kindName")));
      //5.判断充值码充值的金额是否正确
      if (kindNameIn == null || kindNameIn < 0) {
        logger.error("PC查询充值码,充值金额{}错误", kindNameIn);
        return new ResultBean(ResultCode.RechangeCodePayErr1);
      }
      //6.通过兑换规则计算相应饭票数
      Integer amount = platformRechargeService.getMealTicketsByRechargeRuleInfo(4, kindNameIn);
      if (amount == null) {
        logger.error("PC查询充值码{},相应饭票数为空", rechargeCode);
        return new ResultBean(ResultCode.RechangeCodePayErr1);
      }
      map.put("code", rechargeCode);
      map.put("amount", amount);
      return new ResultBean(ResultCode.SUCCESS, JSONObject.toJSON(map));
    } catch (Exception e) {
      logger.error("PC查询充值码充值异常", e);
      return new ResultBean(ResultCode.UNSUCCESS);
    }
  }

  /**
   * h5兑换码充值充值码
   *
   * @param request
   * @return
   * @throws
   * @description （用一句话描述该方法的适用条件、执行流程、适用方法、注意事项 - 可选）
   * @author wangchao
   * @create 2017/2/8 15:33
   */
  @RequestMapping(value = "rechargeCodePay", method = RequestMethod.GET)
  @ResponseBody
  public ResultBean rechargeCodePayForPC(HttpServletRequest request) {
    try {
      String rechargeCode = request.getParameter("code");
      String userId = request.getParameter("userId");
      //0未知，1pc，2ios，3Android,4wap
      String source = request.getParameter("source");
      logger.info("PC充值码{},充值用户ID{}充值,渠道{}", rechargeCode, userId, source);
      //2.校验参数是否为空
      if (StringUtils.isBlank(rechargeCode) || StringUtils.isBlank(userId) || StringUtils.isBlank(source)) {
        logger.error("PC充值码充值参数为空");
        return new ResultBean(ResultCode.ParamException);
      }
      //3.查询充值用户是否存在
      WebUser webUser = userService.getWebUserByUserId(userId);
      if (webUser == null) {
        logger.error("PC充值码充值,充值用户{}不存在", userId);
        return new ResultBean(ResultCode.RechangeCodePayErr2);
      }
      //4.验证充值码是否可用
      ResultBean checkResult =  rechargeLocalService.findValidRechargeInfoByCode(rechargeCode,userId);
      if (checkResult.getCode() != ResultCode.SUCCESS.get_code()) {
        logger.error("PC充值码充值,充值码{}不可用", rechargeCode);
        return checkResult;
      }
      Map rechargeMap = (Map)checkResult.getData();
      //充值码对应的金额
      Integer kindNameIn = Integer.valueOf(String.valueOf(rechargeMap.get("kindName")));
      Map<String, Object> userMap = new HashMap<>();
      userMap.put("userId", webUser.getUserId());
      userMap.put("balance", webUser.getBalance());
      userMap.put("nickName", webUser.getNickName());
      //5.充值码充值操作并返回所得饭票数
      Integer amount;
      try {
        amount = rechargeLocalService.rechargeCodePayOpreate(userMap, rechargeMap, Integer.parseInt(source));
      } catch (Exception e) {
        logger.error("PC充值码充值,充值码{}异常", rechargeCode, e);
        return new ResultBean(ResultCode.UNSUCCESS);
      }
      if (amount == null || amount < 0) {
        return new ResultBean(ResultCode.RechangeCodePayErr1);
      }
      //6.重新查询用户余额，返回pc
      webUser = userService.getWebUserByUserId(userId);
      Map<String, Object> map = Maps.newHashMap();
      map.put("balance", webUser.getBalance());
      map.put("change", amount);
      return new ResultBean(ResultCode.SUCCESS, JSONObject.toJSON(map));
    } catch (Exception e) {
      logger.error("PC充值码充值异常", e);
      return new ResultBean(ResultCode.UNSUCCESS);
    }
  }
}
